import Axios from 'axios';
import Qs from 'qs';

//请求拦截
Axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (config.method == 'post'){
      config.data = Qs.stringify(config.data);
    }
    return config;
  }, 
  function (error) {
    //对请求错误做些什么
    return Promise.reject(error);
  }
);
export default function (
  { 
    method = "post", 
    baseURL = 'http://api.zhonpay.com/',
    url, 
    data = {}, 
    needToken = true,
    needApp=true,
    success,
    error
  }
) {
  if (this.$store.state.axiosSign['sign' + url]) {
    return;
  }
  this.$store.commit(
    'setAxiosSign', 
    {
      key: 'sign' + url,
      value: true
    }
  );
  //验证是否需要token，以及token的正确性

  let obj = {};
  if (needToken) {
    if (!this.$store.state.token) {
      this.$store.commit("setUserSign")
    }
    if (!this.$store.state.token) {
      //token失效，就清除用户登录信息
      this.$store.commit("removeUserSign");
      this.$router.push({ name: "login" });
      return;
    }
    obj.token = this.$store.state.token;
  }
  //obj.app = data; //app包裹参数
  obj =data; //取消app包裹参数JSON.stringify(param)
  Axios({
    method,
    baseURL,
    url,
    data: obj
  }).then((res) => {
    this.$store.commit(
      'setAxiosSign', 
      {
        key: 'sign' + url,
        value: false
      }
    );
    if (res.data.code === -1002 || res.data.code === -1001) {
      //token失效，就清除用户登录信息
      this.$store.commit("removeUserSign");
      this.$router.push({ name: "login" });
        console.log(999)
      return;
    }
    success && success(res);
  }).catch((res) => {
    error && error(res);
  });
}